package com.wbsxch.shiro.shiro;

import com.wbsxch.shiro.dto.UserDTO;
import com.wbsxch.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author: 快乐在角落里
 * @create: 2018-11-12 09:52
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /** 授权 */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        UserDTO userDTO = (UserDTO) principals.getPrimaryPrincipal();
        Set<String> roles = userService.selectUserRoleSet(userDTO.getId());
        Set<String> permissions = userService.selectUserPermissionSet(userDTO.getId());
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    /** 认证 */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        UserDTO userDTO = userService.selectUserByUsername(username);
        if(Objects.isNull(userDTO) || Objects.isNull(userDTO.getPassword()) || Objects.isNull(userDTO.getSalt())){
            throw new UnknownAccountException();
        }
        if(userDTO.getState() == 0){
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo
                (userDTO, userDTO.getPassword(),ByteSource.Util.bytes(userDTO.getSalt()),this.getName());
        return info;
    }
}
